#ifdef __CLING__
R__LOAD_LIBRARY(libyaml-cpp.so)
#endif
#include <TApplication.h>
#include <TGClient.h>
#include <TGButton.h>
#include <TGNumberEntry.h>
#include <TGComboBox.h>
#include <TRootEmbeddedCanvas.h>
#include <TGLabel.h>
#include <TCanvas.h>
#include <TPad.h>
#include <TGraph.h>
#include <TLegend.h>
#include <TTree.h>
#include <TFile.h>
#include <TClonesArray.h>
#include <TSystem.h>
#include <vector>
#include <iostream>
#include <string>
#include<filesystem>
#include <yaml-cpp/yaml.h>
#include "../../../../DataClass/TofData.h"
// #include "../../../../DataClass/TofData.cpp"
using namespace std;
namespace fs=std::filesystem;

long long tsSlc_ToF;
vector<long long> EventNum,coarse_ToF;
int nSig_ToF;
vector<short>pxi_ToF,fee_ToF,iBd_ToF,ch_ToF,shift_ToF,fine_ToF;


// 初始化函数
void InitializeArrays() {
    EventNum.clear();
    tsSlc_ToF = 0;
    coarse_ToF.clear();
    pxi_ToF.clear();
    fee_ToF.clear();
    iBd_ToF.clear();
    ch_ToF.clear();
    shift_ToF.clear();
    fine_ToF.clear();
    nSig_ToF = 0;
}

// 清理函数


void ExtractAndSaveHistograms(
    const char *inputFile,
    TTree *treeRaw_ToF)
{
    TFile *inFile = TFile::Open(inputFile);
    if (!inFile || inFile->IsZombie()) {
        cout << "Error opening file: " << inputFile << endl;
        return;
    }

    TTree *tree = (TTree *)inFile->Get("TofTree");
    if (!tree) {
        cout << "Error getting TofTree from file: " << inputFile << endl;
        inFile->Close();
        return;
    }

    TofData *data = nullptr;
    tree->SetBranchAddress("TofData", &data);

    cout << "Processing file with " << tree->GetEntries() << " entries" << endl;

    // 遍历所有时间片
    for (int iEntry = 0; iEntry < tree->GetEntries(); ++iEntry) {
        tree->GetEntry(iEntry);

        if (data->Pxi.empty()) {
            continue;
        }
        
        // 为当前事件重置数据
        InitializeArrays();
        tsSlc_ToF = data->TimeSliceNumber;
        
        // 遍历所有PXI
        for (size_t iPxi = 0; iPxi < data->Pxi.size(); iPxi++) {
            TofPXI *pxi = &(data->Pxi[iPxi]);
            // 遍历所有FEE
            for (size_t iFee = 0; iFee < pxi->Fee.size(); ++iFee) {
                TofFEE *fee = &(pxi->Fee[iFee]);
                // cout << "FEE" << iFee << endl;

                // 遍历所有通道
                for (size_t iCh = 0; iCh < fee->Channel.size(); ++iCh) {
                    TofChannel* ch = &(fee->Channel[iCh]);
                    // cout << "Channel" << ch->channelId << endl;

                    // 遍历所有聚类
                    for (size_t iCl = 0; iCl < ch->Cluster.size(); ++iCl) {
                        TofCluster* cl = &(ch->Cluster[iCl]);
                        coarse_ToF.push_back(cl->coarseTime);
                        fine_ToF.push_back(cl->fineTime);
                        shift_ToF.push_back(cl->timeOffset);
                        ch_ToF.push_back(ch->channelId);
                        fee_ToF.push_back(fee->feeId);
                        pxi_ToF.push_back(pxi->pxiId);
                        iBd_ToF.push_back(iPxi);
                        EventNum.push_back(iEntry);
                        nSig_ToF++;
                    }
                }
            }
        }

        // 填充树
        if (treeRaw_ToF) {
            treeRaw_ToF->Fill();
        }
    }
    
    inFile->Close();
}

int RawRootData2Root()
{
    // 初始化数组
    InitializeArrays();
    
    YAML::Node config = YAML::LoadFile("../config/config.yaml");
    string homeDir = config["homeDir"].as<string>();
    vector<string> finalFileName = config["finalFileName"].as<vector<string>>();
    int nFile = 0, totalFile = 9999;
    
    for(auto finalFile : finalFileName) {
        cout << "Processing final file: " << finalFile << endl;
        string targetDir = homeDir + finalFile;
        vector<string> rootFiles;
        
        TFile *outFile = new TFile(Form("../RootData/ToF_%s.root", finalFile.c_str()), "recreate");
        if (!outFile || outFile->IsZombie()) {
            cout << "Error creating output file: " << Form("../RootData/ToF_%s.root", finalFile.c_str()) << endl;
            continue;
        }
        
        TTree *treeRaw_ToF = new TTree("treeRaw_ToF", "the data of the ToF");
        treeRaw_ToF->Branch("tsSlc_ToF", &tsSlc_ToF, "tsSlc_ToF/L");
        treeRaw_ToF->Branch("nSig_ToF", &nSig_ToF, "nSig_ToF/I");
        treeRaw_ToF->Branch("ch_ToF", &ch_ToF);
        treeRaw_ToF->Branch("shift_ToF", &shift_ToF);
        treeRaw_ToF->Branch("coarse_ToF", &coarse_ToF);
        treeRaw_ToF->Branch("fine_ToF", &fine_ToF);
        treeRaw_ToF->Branch("fee_ToF", &fee_ToF);
        treeRaw_ToF->Branch("pxi_ToF", &pxi_ToF);
        treeRaw_ToF->Branch("iBd_ToF", &iBd_ToF);
        treeRaw_ToF->Branch("EventNum", &EventNum);
        
        for(const auto& entry : fs::directory_iterator(targetDir)) {
            if(entry.path().extension() == ".root") {
                if(nFile > totalFile) break;
                cout << "Processing file: " << entry.path() << endl;
                ExtractAndSaveHistograms(entry.path().c_str(), treeRaw_ToF);
                cout << "Finished processing file: " << Form("../RootData/ToF_%s.root", finalFile.c_str()) << endl;
                nFile += 1;
            }
        }
        
        outFile->cd();
        treeRaw_ToF->Write("", TObject::kOverwrite);
        outFile->Close();
        delete outFile;
    }
    
    // 清理内存
    // CleanupArrays();
    
    return 0;
}

int main()
{
    RawRootData2Root();
    return 0;
}